//
//  MineViewController.m
//  shusheng
//
//  Created by rimi on 16/7/9.
//  Copyright © 2016年 yuying. All rights reserved.
//

#import "MineViewController.h"
#import "AnimatedTransitioning.h"
#import <LeanCloudFeedback.h>
#import "DetailVerifyView.h"
@interface MineViewController ()<UIViewControllerTransitioningDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate>
{
UIImagePickerController * _imagePickerController;
}

@property (strong, nonatomic) UIAlertController * alert;
@property(strong,nonatomic)UIImageView      *headbackImg;
@property(strong,nonatomic)UIImageView      *headImg;        //头像
@property(strong,nonatomic)UILabel          *userNameLabel;  //用户名
@property(strong,nonatomic)VerifyView       *emailVerifyView;//邮箱验证
@property(strong,nonatomic)VerifyView       *phoneVerifyView;//手机验证
@property(strong,nonatomic)DetailVerifyView *detailVerifyView;
@property(strong,nonatomic)UIButton         *changePswBtn;   //修改密码
//@property(strong,nonatomic)UIView      *achievementView;//成就
@property(strong,nonatomic)UIButton         *logOutBtn;      //登出
@property(strong,nonatomic)UIButton         *feedbackBtn;    //反馈
- (void)initializeInterface;  //初始化用户界面
- (void)updataImg;
- (void)download;
@end

@implementation MineViewController
#pragma mark -- LifeCycle --
- (void)viewDidLoad {
    [super viewDidLoad];
    [self download];
    [self initializeInterface];
    self.transitioningDelegate = self;
    self.modalPresentationStyle = UIModalPresentationCustom;
}


-(void)initializeInterface{
    _imagePickerController = [[UIImagePickerController alloc]init];
    [self.view addSubview:self.headbackImg];
    [self.view addSubview:self.headImg];
    [self.view addSubview:self.userNameLabel];
    [self.view addSubview:self.emailVerifyView];
    [self.view addSubview:self.phoneVerifyView];
    [self.view addSubview:self.changePswBtn];
    [self.view addSubview:self.logOutBtn];
    [self.view addSubview:self.feedbackBtn];
   
}
#pragma mark -- action
- (IBAction)responBtn:(UIButton *)sender {
    NSLog(@"返回");
    [self dismissViewControllerAnimated:YES completion:nil];
}
-(void)logOutAction{
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:KEY_USERNAME];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"psw"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [UIApplication sharedApplication].keyWindow.rootViewController = [[LoginViewController alloc]init];
    
}

-(void)tapPage{
    _alert = self.alert;
    [self presentViewController:_alert animated:YES completion:nil];
    
}
-(void)updataImg{
    [[CDUserManager manager] updateAvatarWithImage:self.headImg.image callback:nil];
}
-(void)download{
  [[CDUserManager manager] getBigAvatarImageOfUser:[AVUser currentUser] block:^(UIImage *image) {
      self.headImg.image = image;
  }];
}
-(void)changePsw{
    NSString *email = [AVUser currentUser].email;
    NSLog(@"%@",email);
    [AVUser requestPasswordResetForEmailInBackground:email block:^(BOOL succeeded, NSError *error) {
        if (succeeded) {
            [MBProgressHUD showSuccess:@"验证邮件已发送，请及时验证"];
        } else {
            
        }
    }];
}
//验证
-(void)phoneVerifyAction{
    [self.view addSubview:self.detailVerifyView];
}
-(void)emailVerifyAction{
    [AVUser requestEmailVerify:[AVUser currentUser].email withBlock:^(BOOL succeeded, NSError *error) {
        [MBProgressHUD showSuccess:@"验证邮件已发送，请及时验证"];
    }];
}
//反馈
-(void)feedbackAction{
    LCUserFeedbackAgent *agent = [LCUserFeedbackAgent sharedInstance];
    /* title 传 nil 表示将第一条消息作为反馈的标题。 contact 也可以传入 nil，由用户来填写联系方式。*/
    [agent showConversations:self title:nil contact:@""];
    LCUserFeedbackViewController *feedbackVc = [[LCUserFeedbackViewController alloc]init];
    feedbackVc.navigationBarStyle = LCUserFeedbackNavigationBarStyleBlue;
 
    
    
}



#pragma mark -- UIImagePickerControllerDelegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
        if ([info[UIImagePickerControllerMediaType] isEqualToString:@"public.image"]) {
            UIImage *originalImage = info[UIImagePickerControllerOriginalImage];
            _headImg.image = originalImage;
            
        }
    }else {
        _headImg.image = info[UIImagePickerControllerEditedImage];
        [self updataImg];
        
    }
    
    [self dismissViewControllerAnimated:YES completion:nil];
}


#pragma make -- UIViewControllerTransitioningDelegate --
-(id<UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source{
    
    return [AnimatedTransitioning transitionWithTransitionType:CircleSpreadTransitionTypePresent];
}

-(id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed{
    return [AnimatedTransitioning transitionWithTransitionType:CircleSpreadTransitionTypeDismiss];
}

#pragma make -- Getter --

-(UIImageView *)headbackImg{
    if (!_headbackImg) {
        _headbackImg = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"backgroundWall.jpg"]];
        _headbackImg.bounds = CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds)/4);
        _headbackImg.center = CGPointMake(CGRectGetMidX(self.view.frame), CGRectGetHeight(self.view.frame)/8+64);
    }
    return _headbackImg;
}


-(UIImageView *)headImg{
    if (!_headImg) {
        _headImg = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"head.jpg"]];
        _headImg.bounds = CGRectMake(0, 0, CGRectGetWidth(self.view.bounds)/4, CGRectGetWidth(self.view.bounds)/4);
        _headImg.center = CGPointMake(CGRectGetMidX(self.view.frame),CGRectGetWidth(self.view.bounds)/4+50);
        _headImg.backgroundColor = [UIColor blackColor];
        _headImg.layer.masksToBounds = YES;
        _headImg.layer.cornerRadius = CGRectGetWidth(self.view.bounds)/8;
        
        UITapGestureRecognizer *tapGesturRecognizer=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapPage)];
        _headImg.userInteractionEnabled = YES;
        [_headImg addGestureRecognizer:tapGesturRecognizer];
        
    }
    return _headImg;
}

-(UILabel *)userNameLabel{
    if (!_userNameLabel) {
        _userNameLabel = [[UILabel alloc]init];
        _userNameLabel.bounds = CGRectMake(0, 0, 150, 30);
        _userNameLabel.center = CGPointMake(CGRectGetMidX(self.view.frame), CGRectGetMaxY(self.headImg.frame)+30);
        _userNameLabel.textAlignment = NSTextAlignmentCenter;
        _userNameLabel.text = [AVUser currentUser].username;
    }
    return _userNameLabel;
}

-(VerifyView *)emailVerifyView{
    if (!_emailVerifyView) {
        _emailVerifyView = [[VerifyView alloc]init];
        _emailVerifyView.bounds = CGRectMake(0, 0, CGRectGetWidth(self.view.bounds)-40, 40);
        _emailVerifyView.center = CGPointMake(CGRectGetMidX(self.view.frame), CGRectGetMaxY(self.userNameLabel.frame)+30);
        
        _emailVerifyView.verifyName.text = @"邮箱";
        NSUInteger email = [[AVUser currentUser].email rangeOfString:@"@"].location;
        _emailVerifyView.verifyContent.text = [[AVUser currentUser].email stringByReplacingCharactersInRange:NSMakeRange(2, email-2) withString:@"****"];
        AVQuery *query = [AVQuery queryWithClassName:@"_User"];
        [query getObjectInBackgroundWithId:[AVUser currentUser].objectId block:^(AVObject *object, NSError *error) {

            NSNumber *emailVerify = (NSNumber *)[object objectForKey:@"emailVerified"];
            BOOL sign = emailVerify.boolValue;
            if (sign) {
                _emailVerifyView.yorNVerifyLabel.text = @"已验证";
                [_emailVerifyView.yorNVerifyLabel setTextColor:[UIColor blueColor]];
                [_emailVerifyView.yorNVerifyImg setImage:[UIImage imageNamed:@"已验证"]];
                return;
            }
            
            UITapGestureRecognizer *tapGesturRecognizer=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(emailVerifyAction)];
            _emailVerifyView.userInteractionEnabled = YES;
            [_emailVerifyView addGestureRecognizer:tapGesturRecognizer];
                    }];
    }
    return _emailVerifyView;
}
-(VerifyView *)phoneVerifyView{
    if (!_phoneVerifyView) {
        _phoneVerifyView = [[VerifyView alloc]init];
        _phoneVerifyView.bounds = CGRectMake(0, 0, CGRectGetWidth(self.view.bounds)-40, 40);
        _phoneVerifyView.center = CGPointMake(CGRectGetMidX(self.view.frame), CGRectGetMaxY(self.emailVerifyView.frame)+30);
        _phoneVerifyView.verifyName.text = @"手机";
        AVQuery *query = [AVQuery queryWithClassName:@"_User"];
        [query getObjectInBackgroundWithId:[AVUser currentUser].objectId block:^(AVObject *object, NSError *error) {
            
            NSString *mobilePhoneNumber = [object objectForKey:@"mobilePhoneNumber"];
            _phoneVerifyView.verifyContent.text = [mobilePhoneNumber stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
            
            NSNumber *phoneVerify = (NSNumber *)[object objectForKey:@"mobilePhoneVerified"];
            BOOL sign = phoneVerify.boolValue;
            
            if (sign) {
                
                _phoneVerifyView.yorNVerifyLabel.text = @"已验证";
                [_phoneVerifyView.yorNVerifyLabel setTextColor:[UIColor blueColor]];
                [_phoneVerifyView.yorNVerifyImg setImage:[UIImage imageNamed:@"已验证"]];
                return;
            }
        }];
        UITapGestureRecognizer *tapGesturRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(phoneVerifyAction)];
        _phoneVerifyView.userInteractionEnabled = YES;
        [_phoneVerifyView addGestureRecognizer:tapGesturRecognizer];
    }
    return _phoneVerifyView;
}
-(UIButton *)changePswBtn{
    if (!_changePswBtn) {
        _changePswBtn = [UIButton createButton:CGRectMake(0, 0, 150, 50) center:CGPointMake(CGRectGetMidX(self.view.frame), CGRectGetMaxY(self.phoneVerifyView.frame)+40) color:[UIColor redColor] cornerRadius:6 masksToBounds:YES title:@"修改密码" tag:0];
        [_changePswBtn addTarget:self action:@selector(changePsw) forControlEvents:UIControlEventTouchUpInside];
    }
    return _changePswBtn;
}


-(UIButton *)logOutBtn{
    if (!_logOutBtn) {
        _logOutBtn = [UIButton createButton:CGRectMake(0, 0, 150, 50) center:CGPointMake(CGRectGetMidX(self.view.frame), CGRectGetMaxY(self.feedbackBtn.frame)+40) color:[UIColor redColor] cornerRadius:6 masksToBounds:YES title:@"退出账号" tag:0];
        [_logOutBtn addTarget:self action:@selector(logOutAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _logOutBtn;
}

-(UIButton *)feedbackBtn{
    if (!_feedbackBtn) {
        _feedbackBtn = [UIButton createButton:CGRectMake(0, 0, 150, 50) center:CGPointMake(CGRectGetMidX(self.view.frame), CGRectGetMaxY(self.changePswBtn.frame)+40) color:[UIColor orangeColor] cornerRadius:6 masksToBounds:YES title:@"用户反馈" tag:0];
        [_feedbackBtn addTarget:self action:@selector(feedbackAction) forControlEvents:UIControlEventTouchUpInside];
        [[LCUserFeedbackAgent sharedInstance] countUnreadFeedbackThreadsWithBlock:^(NSInteger number, NSError *error) {
            if (error) {
                // 网络出错了，不设置红点
            } else {
                // 根据未读数 number，设置红点，提醒用户
            }
        }];
    }
    return _feedbackBtn;
}

-(DetailVerifyView *)detailVerifyView{
    if (!_detailVerifyView) {
        _detailVerifyView = [[DetailVerifyView alloc]init];
        _detailVerifyView.frame = self.view.frame;
        _detailVerifyView.mine = self;
    }
    return _detailVerifyView;
}

- (UIAlertController *)alert {
    if (!_alert) {
        _alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请选择图片来源" preferredStyle:UIAlertControllerStyleActionSheet];
        [_alert addAction:[UIAlertAction actionWithTitle:@"图库" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //获取支持的媒体格式
            NSArray * mediatypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
            // 判断是否支持需要设置的sourceType
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
                // 1、设置图片拾取器上的sourceType
                _imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                // 2、设置支持的媒体格式
                _imagePickerController.mediaTypes = @[mediatypes[0]];
                // 3、是否进入编辑状态
                _imagePickerController.allowsEditing = YES;
                // 4、设置代理
                _imagePickerController.delegate = self;
                [self presentViewController:_imagePickerController animated:YES completion:nil];
            }
        }]];
        [_alert addAction:[UIAlertAction actionWithTitle:@"照相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //获取支持的媒体格式
            NSArray * mediatypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
            // 判断是否支持需要设置的sourceType
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                // 1、设置图片拾取器上的sourceType
                _imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
                // 2、设置支持的媒体格式
                _imagePickerController.mediaTypes = @[mediatypes[0]];
                // 3、是否进入编辑状态
                _imagePickerController.allowsEditing = YES;
                // 4、设置代理
                _imagePickerController.delegate = self;
                [self presentViewController:_imagePickerController animated:YES completion:nil];
            } else {
                UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"系统模拟器暂不能提供照相功能" preferredStyle:UIAlertControllerStyleAlert];
                [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
                [self presentViewController:alert animated:YES completion:nil];
            }
            
        }]];
        [_alert addAction:[UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSArray * mediatypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeSavedPhotosAlbum];
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum]) {
                _imagePickerController.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
                _imagePickerController.mediaTypes = @[mediatypes[0]];
                _imagePickerController.delegate = self;
                _imagePickerController.allowsEditing = YES;
                [self presentViewController:_imagePickerController animated:YES completion:nil];
            }
        }]];
        [_alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    }
    return _alert;
}
@end
